<template>
  <div class="tw-libfloadads" ref="floatads">
    <div ref="floatlay" class="tw-libfloadads-layer"
     v-show="!closeView" style="border:1pa soild #000">
     <!-- 从门户获取数据 -->
     <template v-if="dataIsFromPortal && list.length > 0">
      <a ref="floatlayclose" class="tw-libfloadads-closebtn" @click.stop="handleCloseView"
       v-html="list[0].closeText" v-if="list[0].closeText"></a>
      <a ref="floatlayclose" class="tw-libfloadads-closebtn"
       :style="{width:closeWidth,height:closeHeight,fontSize:closeFontSize,lineHeight:closeHeight,backgroundColor:closeBgColor,zIndex:zIndex}"
       @click.stop="handleCloseView" v-else>×</a>
      <div class="tw-floadads-layer xmenhu" @click="handleClick(list[0])" :style="{'-webkit-line-clamp': lineNum}">
          <img :src="`${$twApp.fileBaseUrl}${list[0].localPath}`"
           :style="{width: imgWidth, height: imgHeight, objectFit: objectFit}"
           :alt="list[0].label ? list[0].label : ''" v-if="list[0].imgUrl">
          <template v-else-if="list.length > 0 && list[0].label">
            <div v-html="list[0].label"></div>
          </template>
      </div>
    </template>
    <!-- 从接口获取数据 -->
    <template v-else-if="data.length > 0">
      <a ref="floatlayclose" class="tw-libfloadads-closebtn" @click.stop="handleCloseView"
       v-html="data[0].closeText" v-if="data[0].closeText"></a>
      <a ref="floatlayclose" class="tw-libfloadads-closebtn"
       :style="{width:closeWidth,height:closeHeight,fontSize:closeFontSize,lineHeight:closeHeight,backgroundColor:closeBgColor,zIndex:zIndex}"
       @click.stop="handleCloseView" v-else>×</a>
      <div class="tw-floadads-layer" @click="handleClick(data[0])" :style="{'-webkit-line-clamp': lineNum}">
          <img :src="data[0].imgUrl"
           :style="{width: imgWidth, height: imgHeight, objectFit: objectFit}"
           :alt="data[0].label ? data[0].label : ''" v-if="data[0].imgUrl">
          <template v-else-if="data.length > 0 && data[0].label">
            <div v-html="data[0].label"></div>
          </template>
      </div>
    </template>
    </div>
  </div>
</template>

<script>
import props from './props'

export default {
  name: 'floading-ads',

  props,

  data () {
    return {
      closeView: false,
      object: [],
      left: 0,
      top: 0,
      interval: 30,
      distance: 2,
      directionX: 1,
      directionY: 1,
      target: '_blank',
      cursor: 'pointer',
      timer: null,
      list: []
    }
  },

  mounted () {
    let vm = this
    if (this.dataIsFromPortal) {
      this.closeView = true
      this.getData().then(() => {
        vm.closeView = false
        vm.init()
      })
    } else {
      this.$nextTick(() => {
        if (vm.data.length > 0) {
          vm.init()
        }
      })
    }
  },

  methods: {
    handleClick (item) {
      if (this.clickFn !== '' && typeof this.clickFn === 'function') {
        this.clickFn(item)
      } else {
        if (item.href) {
          let href = ''
          let hreflink = '?'
          if (item.href.includes('?')) {
            hreflink = '&'
          }
          if (this.useAccred) {
            href = hreflink + this.$twApp.user.accreditUrl
          }
          if (item.target === '_blank') {
            window.open(item.href + href, '_blank')
          } else {
            window.location.href = item.href + href
          }
        }
      }
    },
    handleCloseView () {
      this.closeView = true
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },
    init (data) {
      let that = this
      // let obj1 = document.querySelector('.tw-libfloadads-layer')
      let obj = this.$refs.floatlay

      if (!obj) {
        return
      }
      if (this.object.length > 0) {
        return
      }

      obj.left = parseInt(this.left)
      obj.top = parseInt(this.top)
      obj.interval = parseInt(this.interval)
      obj.distance = parseInt(this.distance)
      obj.directionX = parseInt(this.directionX)
      obj.directionY = parseInt(this.directionY)
      obj.index = this.object.length

      // if (data.length > 0) {
      //   obj.url = data[0].href
      //   obj.target = data[0].target
      //   obj.src = data[0].href

      //   // 事件
      //   if (obj.url !== undefined) {
      //     obj.onclick = function () {
      //       switch (obj.target) {
      //         case '_blank':
      //           window.open(obj.url)
      //           break;
      //         case '_parent':
      //           window.parent.location = obj.url
      //         case '_top':
      //           window.top.location = obj.url
      //           break;
      //         case '_self':
      //           window.location = obj.url
      //           break
      //       }
      //     }
      //   }
      // }
      let objclose = this.$refs.floatlayclose

      obj.t = null
      if (!this.noHoverPause) {
        obj.onmouseover = function () {
          clearInterval(obj.t)
          that.timer = null
          objclose.style.color = that.closeHColor
          objclose.style.background = that.closeHBgColor
        }
        obj.onmouseout = function () {
          obj.t = setInterval(() => {
            that.float(obj.index)
          }, obj.interval)
          that.timer = obj.t
          objclose.style.color = that.closeColor
          objclose.style.background = that.closeBgColor
        }
      }

      obj.style.cursor = this.cursor
      obj.style.position = 'absolute'
      obj.style.padding = this.padding
      obj.style.border = this.border
      obj.style.borderRadius = this.borderRadiu
      obj.style.backgroundColor = this.bgColor
      obj.style.fontSize = this.fontSize
      obj.style.color = this.color
      obj.style.textAlign = this.align
      obj.style.left = obj.left + 'px'
      obj.style.top = obj.top + 'px'
      obj.style.zIndex = parseInt(this.zIndex)
      obj.style.width = this.width || ''
      obj.style.height = this.height || ''
      obj.style.directionX = this.directionX
      obj.style.directionY = this.directionY
      obj.style.overflow = 'hidden'
      this.object = []
      this.object.push(obj)
      //console.log(this.object)
      if (!document.body.hasfload) {
        document.body.appendChild(obj)
        document.body.hasfload = true
      }

      // console.log(obj)
      obj.t = setInterval(() => {
        that.float(obj.index)
      }, obj.interval)
      that.timer = obj.t
    },
    float (index) {
      if (this.closeView && this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
      let pageWidth = document.documentElement.clientWidth
      let pageHeight = document.documentElement.clientHeight
      let scrollLeft = document.documentElement.scrollLeft
      let scrollTop = document.documentElement.scrollTop

      let obj = this.object[index]

      obj.left = obj.left + obj.directionX * obj.distance
      if (obj.left <= scrollLeft) {
        obj.left = scrollLeft
        obj.directionX = 1
      }
      if (obj.left + obj.offsetWidth >= pageWidth + scrollLeft - 1) {
        obj.left = pageWidth + scrollLeft - 1 - obj.offsetWidth
        obj.directionX = -1
      }

      obj.top = obj.top + obj.directionY * obj.distance
      if (obj.top <= scrollTop) {
        obj.top = scrollTop
        obj.directionY = 1
      }
      if (obj.top + obj.offsetHeight >= pageHeight + scrollTop - 1) {
        obj.top = pageHeight + scrollTop - 1 - obj.offsetHeight
        obj.directionY = -1
      }

      obj.style.left = obj.left + 'px'
      obj.style.top = obj.top + 'px'
    },

    /***
     * 从接口获取数据
     */
    async getData () {
      let params = {
        condition: {
          siteId: this.$siteConfig.siteId,
          // siteId: 'cF5j8CgLY3X7',
          pageId: '',
          pageIdList: [],
          status: '1',
          showWindow: '1'
        },
        orderList: ['createTime desc', 'lastModifyTime asc'],
        pageNo: '1',
        pageSize: '1'
      }
      params.condition.pageId = this.moudleId
      await window.axios.post(`${window.$twApp.gateway}/unified-portal/document/getDocumentListBySiteId`, params).then(resp => {
        this.list = []
        if (resp.data.serverResult.resultCode && resp.data.result && resp.data.result.list) {
          this.list = resp.data.result.list.map((item, idx) => {
            return {
              documentId: item.documentId,
              // title: item.title,
              label: item.title,
              // createTime: item.createTime,
              // date: window.$ui.dateFormat(item.lastModifyTime, 'yyyy-mm-dd'),
              // cover: item.coverIcon,
              // pageId: item.pageId,
              // publish: item.publish,
              // type: item.type,
              // status: item.status,
              // source: item.source,
              href: this.detaillUrl ? `${this.detaillUrl}?pageId=${item.pageId}&documentId=${item.documentId}&parentId=${this.parentId}&subMenuVisibal=${this.subMenuVisibal}&dropBgColor=${this.dropBgColor}` : '#',
              target: '_blank'
            }
          })


          // let total = resp.data.result.total
          // this.$emit('update:total', total)

        } else {
        }
      }).catch(e => {
        this.$ui.msg({
          type: 'error',
          message: '获取列表失败'
        })
      })
    }
  },
  beforeDestroy () {
    if (this.timer) {
      window.clearInterval(this.timer)
      this.timer = null
    }
  },
  watch: {
    dataIsFromPortal: {
      deep: true,
      handler () {
        if (this.dataIsFromPortal) {
          this.getData()
        }
      }
    },
    moudleId: {
      deep: true,
      handler () {
        this.getData()
      }
    },
    data: {
      deep: true,
      handler () {
        if (!this.dataIsFromPortal) {
          document.body.hasfload = false
          this.init(this.data)
        }
      }
    },
  }
}
</script>

<style lang="scss">
@import './css/index.scss';
</style>
